<template>
  <div style="overflow-y: auto; height: 100%; position: relative">
    <div v-if="uploadLocalFileList.length">
      <div class="time">当前</div>
      <publish-table-current :data="uploadLocalFileListFormat" />
      <a-divider></a-divider>
    </div>
    <div>
      <template v-for="{ item, time } in batch">
        <div class="time">{{ time }}</div>
        <publish-table :data="item" @invalid="onInvalid" />
        <a-divider></a-divider>
      </template>
      <div style="text-align: center">
        <infinite-loading @infinite="load">
          <template #complete> 没有更多了 </template>
          <template #error>
            <a-space> 加载失败 </a-space>
          </template>
          <template #spinner>
            <a-spin :spinning="true"></a-spin>
          </template>
        </infinite-loading>
      </div>
    </div>
    <div
      v-if="notData"
      style="
        display: flex;
        justify-content: center;
        align-items: center;
        position: absolute;
        z-index: 2;
        top: 0;
        left: 0;
        right: 0;
        bottom: 0;
        background-color: #fff;
      "
    >
      <a-spin :spinning="loading">
        <a-empty
          :image="notPublished"
          :description="loading ? '加载中...' : '暂无发布'"
        />
      </a-spin>
    </div>
  </div>
</template>
<script setup>
import { computed, ref } from 'vue'
import PublishTable from './publish-table.vue'
import PublishTableCurrent from './publish-table-current.vue'
import notPublished from '@/assets/images/not-published.png'
import { useUploadLocalFileList } from './provide-context.js'
import InfiniteLoading from 'v3-infinite-loading'
import 'v3-infinite-loading/lib/style.css'
import calendar from 'dayjs/plugin/calendar'
import dayjs from 'dayjs'
import 'dayjs/locale/zh-cn'
dayjs.locale('zh-cn')
dayjs.extend(calendar)

import { getFileInfo, uploadRecord } from '@/api/db.js'
import { useDbType } from './provide-context.js'
/**
 * 全局数据
 */
let uploadLocalFileList = useUploadLocalFileList()
// let importFileList = useImportFileList()
let calendarOptions = {
  sameDay: '[今天] hh:mm:ss ', // The same day ( Today at 2:30 AM )
  nextDay: '[明天] hh:mm:ss', // The next day ( Tomorrow at 2:30 AM )
  nextWeek: 'dddd hh:mm:ss', // The next week ( Sunday at 2:30 AM )
  lastDay: '[昨天] hh:mm:ss', // The day before ( Yesterday at 2:30 AM )
  lastWeek: 'dddd hh:mm:ss', // Last week ( Last Monday at 2:30 AM )
  sameElse: 'YYYY/MM/DD hh:mm:ss', // Everything else ( 7/10/2011 )
}

/**
 * 数据
 */
//历史数据
let loading = ref(false)
let history = ref([])
let batch = computed(() => {
  let batch = {}
  history.value.forEach(item => {
    let { createdTime } = item
    if (!batch[createdTime]) {
      batch[createdTime] = []
    }
    let percent = 100
    let status
    if (item.saveStatus === 1) {
      // status = 'active'
    }
    if (item.saveStatus === 2) {
      status = 'exception'
    }
    if (item.saveStatus === 0) {
      status = 'active'
      percent = 90 //parseInt(90 * Math.random())
    }
    batch[createdTime].push({
      name: item.fileName,
      type: item.fileType,
      status,
      isHistory: true,
      id: item.id,
      percent,
    })
  })
  return Object.keys(batch)
    .sort((a, b) => {
      return new Date(b).getTime() - new Date(a).getTime()
    })
    .map(key => {
      let time = key
      try {
        // console.log(time, key, dayjs(key).calendar(null, calendarOptions))
        // console.log(key)
        time = dayjs(key).calendar(null, calendarOptions)
      } catch (e) {}
      return { time, item: batch[key] }
    })
})
//当前上传数据
let uploadLocalFileListFormat = computed(() => {
  return uploadLocalFileList.value.map(file => {
    return {
      name: file.name,
      status:
        file.status === 'error' ||
        (file.status === 'done' && !file?.response?.success)
          ? 'exception'
          : file.percent === 100
            ? null
            : 'active',
      id: file.uuid,
      percent: parseInt(file.percent),
    }
  })
})

let page = 1
let pageSize = 10
let completed = ref(false)
let dbType = useDbType()
async function load(event) {
  loading.value = true
  try {
    let result = await uploadRecord(
      {
        pageNum: page,
        pageSize,
        dataType: 'file',
      },
      dbType,
    )
    let json = result?.data?.records || []
    history.value.push(...json)
    if (json.length < 10) {
      event.complete()
      completed.value = true
    } else {
      event.loaded()
      page++
    }
  } catch (error) {
    event.error()
  }
  loading.value = false
}
let notData = computed(() => {
  return uploadLocalFileList.value.length === 0 && history.value.length === 0
})
//删除数据
function onInvalid(id) {
  history.value = history.value.filter(item => item.id !== id)
}
</script>
<style lang="less" scoped>
.time {
  color: rgba(0, 0, 0, 0.15);
  text-align: center;
  margin-bottom: 6px;
}
.ant-divider {
  margin: 20px 0;
}
</style>
